package PatientLookupUtil;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import persistent.Db4oServletListener;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;

import LoginUtil.User;

/**
 * Servlet implementation class ViewPatientServlet
 */
public class ViewPatientServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewPatientServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ObjectContainer container = 
	        (ObjectContainer)request.getAttribute(Db4oServletListener.KEY_DB4O_SESSION);
		
		final String patientName = request.getParameter("userdrop");
		
		// set up the predicate to query the database for the patient
		final String[] splits = patientName.split(" ");	// split the string around spaces hopefully to separate first and last name
				
		Predicate<User> pred = new Predicate<User>() {
					
					      public boolean match(User patient){
					        return patient.getUserType() == User.UserType.Patient
					          && patient.getFirstName().equalsIgnoreCase(splits[0])
					          && patient.getLastName().equalsIgnoreCase(splits[1]);}};	
					          
		ObjectSet<User> rs = container.query(pred);
		if(rs.size() != 1) {
			PrintError();
		} else {
			// set an attribute for the jsp to get
			request.getSession().removeAttribute("KEY_VIEWING_PATIENT");
			request.getSession().setAttribute("KEY_VIEWING_PATIENT", rs.next());
			
			// redirect to the viewPatient jsp
			response.sendRedirect("viewPatient.jsp");
		}
		
		
	}
	

	private void PrintError() {
		System.out.println("ERROR: non-unique patient name in ViewPatientServlet");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
